package com.mobilezu.mobile.pushserver.dao.hibernate;

import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.mobilezu.mobile.pushserver.dao.PushUserDao;
import com.mobilezu.mobile.pushserver.model.PushUser;
import com.mobilezu.mobile.pushserver.service.UserNotFoundException;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class PushUserDaoHibernate extends HibernateDaoSupport implements
		PushUserDao {

	public PushUser getPushUser(Long id) {
		return (PushUser) getHibernateTemplate().get(PushUser.class, id);
	}

	public PushUser savePushUser(PushUser pushUser) {
		getHibernateTemplate().saveOrUpdate(pushUser);
		getHibernateTemplate().flush();
		return pushUser;
	}

	public void removePushUser(Long id) {
		getHibernateTemplate().delete(getPushUser(id));
	}

	public boolean exists(Long id) {
		PushUser pushUser = (PushUser) getHibernateTemplate().get(
				PushUser.class, id);
		return pushUser != null;
	}

	public List<PushUser> getPushUsers() {
		return getHibernateTemplate().find(
				"from PushUser u order by u.updatedDate desc");
	}

	public PushUser getPushUserByUsername(String pushUsername)
			throws UserNotFoundException {
		List pushUsers = getHibernateTemplate().find(
				"from PushUser where username=?", pushUsername);
		if (pushUsers == null || pushUsers.isEmpty()) {
			throw new UserNotFoundException("User '" + pushUsername
					+ "' not found");
		} else {
			return (PushUser) pushUsers.get(0);
		}
	}

}
